package com.hugothauan.cowboyshoot;

import com.game.ThauanFramework.Game;
import com.hugothauan.cowboyshoot.Managers.GameManager;
import com.hugothauan.cowboyshoot.Rede.Server;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;


public class CenaDeJogo extends View implements Runnable{

	private String TAG = "GameScene";
	private Thread mainThread;
	private int interval = 10;
	private boolean running = true;
	
	private static GameManager gameManager;
	
	public CenaDeJogo(Context context) 
	{
		super(context);	
		running = true;
		this.setFocusable(true);
		Server.getInstance().Setup();
		
		this.gameManager = new GameManager();
		
		Start();	
	}
	
	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh)
	{		
		MinhasCoisas.setCanvasHeight(h);
		MinhasCoisas.setCanvasWidth(w);
		
		gameManager.Configurar(w, h);
		
		mainThread = new Thread(this);
		mainThread.start();
		
		Log.i(TAG, "on size Changed");
		
		if(Server.getInstance().isServer)
		{
			MinhasCoisas.Show("Sou servidor");
			// Primeira mensagem do Servidor Aqui
		}
	}
	
	public boolean onTouchEvent(MotionEvent event) 
	{
		boolean rtn = gameManager.onTouch(this, event);
		return rtn;
	}
	//------------------------------------------------------------- START
	public void Start()
	{
		MinhasCoisas.Show("Start de Cena de jogo");

	}
	//------------------------------------------------------------- UPDATE
	public void Update()
	{	
		if(gameManager != null)
		gameManager.Atualizar();
		
	}
	// -------------------------------------------------- Draw
	@Override
	public void draw(Canvas canvas) 
	{
		super.draw(canvas);
		
		if(gameManager != null)
		gameManager.Desenhar(canvas);
	}
	
	public static void HandleFromServer(String msg)
	{
		// Trabalhar com a mensagem recebida do Servidor
		if(gameManager != null)
		gameManager.HandleFromServer(msg);
	}
	
	public void SetAlive(boolean bool)
	{
		this.running = bool;
	}
		
	@Override
	public void run() {
		
		while(running)
		{
			try
			{
				Thread.sleep(interval);
			}
			catch(InterruptedException e)
			{
				running = false;
				Log.i(TAG, "Erro no processo de Thread", e);
			}
			
			Update();
			postInvalidate();
		
		}

	}
}
